import axios from 'axios'
import { ElMessage } from 'element-plus'

// Create axios instance
const request = axios.create({
  baseURL: '/api',  // Forwarded to backend via vite proxy
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// Request interceptor
request.interceptors.request.use(
  config => {
    // Add token here if needed
    // const token = localStorage.getItem('token')
    // if (token) {
    //   config.headers.Authorization = `Bearer ${token}`
    // }
    return config
  },
  error => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// Response interceptor
request.interceptors.response.use(
  response => {
    const res = response.data
    
    // Check based on backend returned code (2xx is success)
    if (res.code && (res.code < 200 || res.code >= 300)) {
      ElMessage.error(res.message || 'Request failed')
      return Promise.reject(new Error(res.message || 'Request failed'))
    }
    
    // Return complete response object, keeping data, count, total fields
    return res
  },
  error => {
    console.error('Response error:', error)
    
    if (error.response) {
      switch (error.response.status) {
        case 400:
          ElMessage.error(error.response.data.message || 'Invalid request parameters')
          break
        case 404:
          ElMessage.error('Resource not found')
          break
        case 500:
          ElMessage.error('Server error, please try again later')
          break
        default:
          ElMessage.error(error.response.data.message || 'Network error')
      }
    } else {
      ElMessage.error('Network connection failed, please check your network settings')
    }
    
    return Promise.reject(error)
  }
)

export default request

